using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DesktopWidgetApp.Server.Models;
using DesktopWidgetApp.Server.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;

namespace DesktopWidgetApp.Server.API.Controllers
{
    /// <summary>
    /// 状态控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class StatusController : BaseController
    {
        private readonly IStatusService _statusService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="statusService">状态服务</param>
        public StatusController(IStatusService statusService)
        {
            _statusService = statusService;
        }

        /// <summary>
        /// 获取当前用户的最新状态
        /// </summary>
        /// <returns>用户的最新状态</returns>
        [HttpGet("current")]
        public async Task<ActionResult<ServerStatus>> GetCurrentUserLatestStatus()
        {
            var userId = GetCurrentUserIdOrThrow();
            var status = await _statusService.GetLatestStatusByUserIdAsync(userId);
            if (status == null)
            {
                return NotFound();
            }
            return Ok(status);
        }

        /// <summary>
        /// 添加或更新当前用户的状态
        /// </summary>
        /// <param name="status">状态对象</param>
        /// <returns>添加或更新后的状态</returns>
        [HttpPost]
        public async Task<ActionResult<ServerStatus>> AddOrUpdateStatus(ServerStatus status)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var userId = GetCurrentUserIdOrThrow();
            status.UserId = userId; // 确保状态属于当前用户
            var result = await _statusService.AddOrUpdateStatusAsync(status);
            return CreatedAtAction(nameof(GetCurrentUserLatestStatus), result);
        }

        /// <summary>
        /// 获取指定用户的状态历史（管理员权限）
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns>状态历史列表</returns>
        [HttpGet("user/{userId}/history")]
        [Authorize(Roles = "Admin,SuperAdmin")] // 保留特定角色授权
        public async Task<ActionResult<IEnumerable<ServerStatus>>> GetStatusHistoryByUserId(
            Guid userId, 
            [FromQuery] DateTime startDate, 
            [FromQuery] DateTime endDate)
        {
            var history = await _statusService.GetStatusHistoryByUserIdAsync(userId, startDate, endDate);
            return Ok(history);
        }
    }
}